package com.example.databindingdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.example.databindingdemo.databinding.ItemBinding;

import java.util.List;

public class Adapter extends ArrayAdapter<Bean> {
    private int resourceid;
    private ItemBinding bin;
    public Adapter(@NonNull Context context, int resource, @NonNull List<Bean> objects) {
        super(context, resource, objects);
        resourceid =resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
//        获取单个的bean对象和以前listview的写法一致
        Bean bean = getItem(position);
//        下面这么做是为了优化listview的性能
        bin = null;
        if (convertView == null){
            bin = DataBindingUtil.inflate(LayoutInflater.from(getContext()),resourceid,parent,false);
        }else {
            bin = DataBindingUtil.getBinding(convertView);
        }
        bin.setBean(bean);
        return bin.getRoot();
    }
}
